
#include "iot/thing.h"
#include "application.h"
#include "custom_display.h"
#include <esp_log.h>
#include <lvgl.h>

#include "assets/lang_config.h"

#define TAG "AlarmIot"

namespace iot {

// 这里仅定义 AlarmIot 的属性和方法，不包含具体的实现
class AlarmIot : public Thing {
    private:
    esp_timer_handle_t clock_timer_handle_ = nullptr;
    int total_time_ = 0;
    int alarm_count_ = 0;
    void InitializeEvent() {
        esp_timer_create_args_t clock_timer_args = {
            .callback = [](void* arg) {
                AlarmIot* instance = (AlarmIot*)(arg);
                instance->UpdateAlarmCount();
            },
            .arg = this,
            .dispatch_method = ESP_TIMER_TASK,
            .name = "AlarmCUpdateTimer",
            .skip_unhandled_events = true
        };
        esp_timer_create(&clock_timer_args, &clock_timer_handle_);
        esp_timer_start_periodic(clock_timer_handle_, 1000000);
    }
    void UpdateAlarmCount() {
        if (alarm_count_ > 0) {
            // long long current_time = esp_timer_get_time(); // 获取当前时间（微秒）
            // static long long last_second_update_time = current_time; // 静态变量，记录上次秒更新的时间
            alarm_count_--;
            ESP_LOGI(TAG, "Alarm count: %d", alarm_count_);
            auto display = Board::GetInstance().GetDisplay();
            CustomLcdDisplay* custom_display = (CustomLcdDisplay*)(display);
            int progress = static_cast<float>(alarm_count_ * 100) / total_time_;
            custom_display->updateArcAndLabel(progress, progress == 0 ? "" : (std::to_string(alarm_count_)+"秒").c_str());
            if (alarm_count_ == 0) {
                // 这里可以添加闹钟响起的逻辑
                ESP_LOGI(TAG, "Alarm is ringing!");
                auto& app = Application::GetInstance();
                // app.PlaySound(Lang::Sounds::P3_SUCCESS);
                app.Alert("Alarm", "Time's up!", "happy", Lang::Sounds::P3_ACTIVATION);
            }
        }
    }

    void StopAlarm() {
        alarm_count_ = 0;
        ESP_LOGI(TAG, "Alarm has been stopped.");
    }
public:
    AlarmIot() : Thing("Alarm", "一个闹钟, 可以定时提醒") {
        InitializeEvent();

        // 定义设备的属性
        properties_.AddStringProperty("AlarmStatus", "当前闹钟的状态", [this]() -> std::string {
            auto& app = Application::GetInstance();
            return std::string(alarm_count_ > 0 ? "启用" : "未启用");
        });

        // 定义设备可以被远程执行的指令
        methods_.AddMethod("SetAlarm", "设置一个倒计时", ParameterList({
            Parameter("seconde_from_now", "倒计时多少秒以后响", kValueTypeNumber, true)
        }), [this](const ParameterList& parameters) {
            auto& app = Application::GetInstance();
            int seconde_from_now = parameters["seconde_from_now"].number();
            total_time_ = seconde_from_now;
            alarm_count_ = seconde_from_now;
        });
    }
};

} // namespace iot

DECLARE_THING(AlarmIot);

